//
//  FHUserAccessViewModel.swift
//  WeiBo
//
//  Created by qfh on 16/7/12.
//  Copyright © 2016年 qiufuhe. All rights reserved.
//

import UIKit

typealias boolBlack = (isBool: Bool)->()

class FHUserAccessViewModel: NSObject {
    /// 单例
    static let sharedUserAccessViewModel: FHUserAccessViewModel = FHUserAccessViewModel()
    
    /// 模型
    var userAccess: FHUserAccount? {
    
        return FHUserAccount.loadUserAccount()
    
    }
    
    
    /// 判断是否登录
    var isLogin:Bool {
    
        return expiresDate != nil
        
    }
    
    /// 计算过期日期  过期了  日期为空
    var expiresDate: NSDate? {
    
        guard let expires = userAccess?.expiresDate else{
        
            return nil
        }
        
        let comp: NSComparisonResult = expires.compare(NSDate())

        if comp == NSComparisonResult.OrderedDescending {
        
            return expires
            
        }
    
    
    return nil
    
    }
    
    
    
   private override init() {
        super.init()
    }
    
    
    
    /**
     获取access
     
     - parameter code: code
     */
    func requesAccess_token(code: String, cellBack:(isRequest: Bool)->()) {
        
        
        FHNetTools.shearedNetTools.requestAccess_token(code, cellBack: { (response, error) -> () in
            
            if !(error == nil) {
                
                print(error)
                
                cellBack(isRequest: false)
                
                return
            }
            
        
            
            let account = FHUserAccount(dict: response as! [String : AnyObject])
            
            self.requestUserInfo(account,cellBack: cellBack)
            
            
            
            
        })
        
    }
    
    
    /**
     获取用户信息
     
     - parameter account: 用户模型
     */
    func requestUserInfo(account: FHUserAccount, cellBack:(isRequest: Bool)->()) {
        
        
        
        
        FHNetTools.shearedNetTools.requestUserInfo(account, cellBack: { (response, error) -> () in
            
            if !(error == nil) {
                
                print(error)
                
                cellBack(isRequest: false)
                
                return
            }
            
            
            guard let dic = response else {
                print("不是json")
                cellBack(isRequest: false)
                return
            }
            
            //            print(dic)
            
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            
            account.name = name as? String
            
            account.avatar_large = avatar_large as? String
                        
            print(account)
            
            cellBack(isRequest: account.saveUserAccount())
            
            
            
        })
        
        
        
        
    }

    
    
    

}
